package com.chuantou.yuba.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuantou.yuba.R;

public class LetterBar extends LinearLayout implements OnTouchListener {

	private static final String[] LETTERS = new String[] { "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
			"T", "U", "V", "W", "X", "Y", "Z" };

	private LinearLayout mLetterLayout;

	private String mLastLetter;

	private OnLetterChangedListener listener;

	public static interface OnLetterChangedListener {
		/**
		 * 字母改变
		 * 
		 * @param letter
		 */
		public void onLetterChanged(String letter);
	}

	public LetterBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		setupViews();
	}

	public LetterBar(Context context) {
		super(context);
		setupViews();
	}

	private void setupViews() {
		LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.letter_bar, this, true);
		mLetterLayout = (LinearLayout) findViewById(R.id.letters);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams.weight = 1;
		// 循环加入字母
		for (int i = 0; i < LETTERS.length; i++) {
			TextView letterView = (TextView) inflater.inflate(R.layout.letter, null);
			letterView.setText(LETTERS[i]);
			mLetterLayout.addView(letterView, i, layoutParams);
		}
		mLetterLayout.setOnTouchListener(this);
	}

	public void setOnLetterChangedListener(OnLetterChangedListener letterChangedListener) {
		this.listener = letterChangedListener;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		float y = event.getY();
		int height = getHeight();
		int position = (int) (y / height * LETTERS.length);
		if (position < 0 || position >= LETTERS.length)
			return false;
		String letter = LETTERS[position];
		if (!letter.equals(mLastLetter)) {
			mLastLetter = letter;
			if (listener != null) {
				listener.onLetterChanged(letter);
			}
		}
		return false;
	}

}
